package com.learn.dataandfile.share_storage

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.exercise.struct.base.BaseActivity
import com.exercise.struct.viewmodel.BaseViewModel
import com.learn.dataandfile.databinding.ActivityShareStorageBinding

class ShareStorageActivity : BaseActivity<BaseViewModel, ActivityShareStorageBinding>() {
    override val bindingInflater: (LayoutInflater) -> ActivityShareStorageBinding
        get() = ActivityShareStorageBinding::inflate
    override val modelClass: Class<BaseViewModel>
        get() = BaseViewModel::class.java

    //注册一个单选模式的 Photo Picker Activity Launcher
    private val pickMedia = registerForActivityResult(
        ActivityResultContracts.PickVisualMedia()
    ) { uri ->
        if (uri != null) {
            Log.d("Photo Picker", "Selected URI：$uri")
        } else {
            Log.d("Photo Picker", "No media selected")
        }
    }

    private fun doSingleSelectMediaItem() {
        val photoPickerAvailable =
            ActivityResultContracts.PickVisualMedia.isPhotoPickerAvailable(this)
        Log.d("Photo Picker", "photoPickerAvailable：$photoPickerAvailable")
        //即可选择图片，也可选择视频
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageAndVideo))
        //仅选择图片
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
        //仅选择视频
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.VideoOnly))
        // 仅选择指定MIME类型的视频或图片
        val mimeType = "image/gif"
        pickMedia.launch(
            PickVisualMediaRequest(
                ActivityResultContracts.PickVisualMedia.SingleMimeType(
                    mimeType
                )
            )
        )
    }

    //注册多选模式的Photo Picker启动器（这里限定最多选取3个媒体文件）
    private val pickMedias =
        registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(3)) { uris ->
            if (uris.isNotEmpty()) {
                Log.d("Photo Picker", "Number of items selected: ${uris.size}")
            } else {
                Log.d("Photo Picker", "No media selected")
            }

        }

    private fun doMultipleSelectMediaItems() {
        //和单选的启动方式一样
        pickMedias.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageAndVideo))
    }

    override fun initData() {
    }

    override fun initView() {
    }

    fun onClick(view: View) {
        when (view.id) {
            binding.btnSingleSelect.id -> {//单选
                doSingleSelectMediaItem()
            }

            binding.btnMultipleSelect.id -> {//多选
                doMultipleSelectMediaItems()
            }

            binding.btnCreateFile.id -> {//创建文件
                doCreateFile(Uri.parse(""))
            }
            binding.btnOpenFile.id ->{
                doOpenFile()
            }
            else -> {}
        }
    }

    private val REQUEST_CODE_OPEN_FILE = 2
    private fun doOpenFile() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            putExtra(DocumentsContract.EXTRA_INITIAL_URI,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        }
        startActivityForResult(intent,REQUEST_CODE_OPEN_FILE)
    }

    private val CREATE_FILE = 1
    private fun doCreateFile(pickerInitialUri:Uri) {
        val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "application/pdf"
            putExtra(Intent.EXTRA_TITLE, "invoice.pdf")

            //可选
            putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri)
        }
        startActivityForResult(intent,CREATE_FILE)
    }

    companion object {
        fun start(context: Context) {
            Intent(context, ShareStorageActivity::class.java).also {
                context.startActivity(it)
            }
        }
    }

}